<template>
  <div>
    <canvas ref="waveCanvas" @click="resetWave" width="400" height="200"></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvas: null,
      ctx: null,
      amplitude: 50, // 振幅
      frequency: 0.02, // 频率
      speed: 0.01, // 速度
      offset: 0, // 偏移量
      waves: 5, // 波浪数量
    };
  },
  mounted() {
    this.canvas = this.$refs.waveCanvas;
    this.ctx = this.canvas.getContext('2d');
    this.animate();
  },
  beforeDestroy() {
    cancelAnimationFrame(this.animationFrame);
  },
  methods: {
    drawWave() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

      // 绘制波浪
      for (let i = 0; i < this.waves; i++) {
        let waveAmplitude = this.amplitude * (1 - i * 0.2); // 递减的振幅
        let waveOffset = i * Math.PI * 2 / this.waves; // 波浪之间的相位偏移

        for (let x = 0; x < this.canvas.width; x++) {
          let y = Math.sin((x / this.canvas.width + this.offset + waveOffset) * this.frequency * Math.PI * 2) * waveAmplitude + this.canvas.height / 2;
          y = Math.max(0, Math.min(y, this.canvas.height));

          // 使用线性插值来平滑点之间的过渡
          this.ctx.fillStyle = `rgba(0, 0, 255, ${(1 - Math.abs((y - this.canvas.height / 2) / (this.canvas.height / 2)))})`;
          this.ctx.fillRect(x, y - 2, 1, 4);
        }
      }

      // 更新偏移量以模拟波浪的移动
      this.offset += this.speed;

      // 如果波浪移出视口，则重置它
      if (this.offset > 1) {
        this.offset = 0;
      }
    },
    animate() {
      this.animationFrame = requestAnimationFrame(this.animate);
      this.drawWave();
    },
    resetWave() {
      // 重置波浪以开始新的动画周期
      this.offset = 0;
    },
  },
};
</script>

<style scoped>
canvas {
  border: 1px solid #000;
}
</style>